#include "refreshtimer.h"
#include <QTimer>
#include "free-cube/freecube.h"
#include "free-cube/airefreshee.h"
#include "free-cube/logger.h"


using namespace fc;

RefreshTimer::RefreshTimer(int ms, QObject *parent) :
    QThread(parent), is_started_ (false),
    msec_(ms)

{
}

void RefreshTimer::run(){
    int time_elapsed = 0;
    while (is_started_){
        // emit refresh_event(time_elapsed);
        refresh_all();
        fc::msec_sleep(msec_);
        time_elapsed += msec_;
    }
}

void RefreshTimer::start_timer(){
    is_started_ = true;
    start();
}

void RefreshTimer::stop_timer(){
    is_started_ = false;
}

void RefreshTimer::submit(AIRefreshee * refreshee){
    submitters_.append(refreshee);
}

void RefreshTimer::unsubmit(AIRefreshee * refreshee){
    submitters_.removeAll(refreshee);
}

void RefreshTimer::refresh_all(){
    foreach (AIRefreshee * r, submitters_) r->refresh(msec_);
}

void RefreshTimer::unsubmit_all(){
    fc::log("unsubmitted all");
    foreach (AIRefreshee * r, submitters_) r->reset_refresher();
    submitters_.clear();
}
